package client;

import java.io.IOException;

import server.Message;
import client.ClientLib.ClientType;
import client.ClientLib.FailedConnectException;
import client.ClientLib.OnSub;

public class SubRandom {

	private static class Counter implements OnSub {

		private int count = 0;
		private int misses = 0;
		private long last = -1;

		@Override
		public void onSubReceive(Message m) {
			count++;
			if (last != -1 && last != m.seq - 1) {
				//System.err.println(last + " | " + m.seq);
				misses++;
			}
			last = m.seq;
		}

	}

	public static void main(String[] args) {
		String host = (args.length > 0) ? args[0] : "localhost";
		int port = (args.length > 1) ? Integer.parseInt(args[1]) : 15000;
		int numClients = (args.length > 2) ? Integer.parseInt(args[2]) : 1;
		String tag = (args.length > 3) ? args[3] : "a";
		
		ClientLib[] clients = new ClientLib[numClients];
		Counter[] counters = new Counter[numClients];
		
		for (int i = 0; i < clients.length; i++) {
			clients[i] = new ClientLib(tag + i, host, port, ClientType.SUBSCRIBER);
			counters[i] = new Counter();
			try {
				clients[i].subscribe("random", counters[i]);
			}
			catch (IOException e) {
				e.printStackTrace();
				//System.exit(-1);
			}
			catch (FailedConnectException e) {
				System.err.println(clients[i].myId + " failed to connect");
			}
		}
		
		int[] prev = new int[counters.length];
		for (int j = 0; j < 30; j++) {
			for (int i = 0; i < counters.length; i++) {
				System.out.printf("%d w%d %d %d\n", j, i, counters[i].count - prev[i], counters[i].misses);
				prev[i] = counters[i].count;
			}
			try {
				Thread.sleep(1000);
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int i = 0; i < counters.length; i++) {
			System.out.printf("Total w%d: %d\n", i, counters[i].count);
		}
		System.exit(0);
	}
}
